package com.shycloud.mido.member.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.common.util.NetworkUtil;
import com.shycloud.mido.common.util.SnowFlakeUtil;
import com.shycloud.mido.member.api.entity.BasicAppShoppingCart;
import com.shycloud.mido.member.api.entity.BasicAppShoppingItem;
import com.shycloud.mido.member.api.entity.BasicAppShoppingOrder;
import com.shycloud.mido.member.api.entity.BasicGoodsInfo;
import com.shycloud.mido.member.api.entity.BasicProductInfo;
import com.shycloud.mido.member.api.entity.BasicShoppingBanner;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MemberOrderApp;
import com.shycloud.mido.member.api.entity.MemberOrderDetailApp;
import com.shycloud.mido.member.api.feign.RemoteMusicService;
import com.shycloud.mido.member.api.vo.AppAppShoppingCartVO;
import com.shycloud.mido.member.api.vo.AppShoppingOrderVO;
import com.shycloud.mido.member.api.vo.AppShoppingPurchaseVO;
import com.shycloud.mido.member.api.vo.GoodsInfoVO;
import com.shycloud.mido.member.api.vo.MemberOrderAppVO;
import com.shycloud.mido.member.api.vo.RecommendVO;
import com.shycloud.mido.member.api.vo.VipMemberVO;
import com.shycloud.mido.member.constants.ShoppingStockConstants;
import com.shycloud.mido.member.mapper.BaseMusicAuditionCodeMapper;
import com.shycloud.mido.member.mapper.BasicGoodsCategoryMapper;
import com.shycloud.mido.member.mapper.BasicGoodsInfoMapper;
import com.shycloud.mido.member.mapper.BasicProductInfoMapper;
import com.shycloud.mido.member.mapper.BasicProductsComboMapper;
import com.shycloud.mido.member.mapper.BasicShoppingBannerMapper;
import com.shycloud.mido.member.mapper.BasicShoppingCartMapper;
import com.shycloud.mido.member.mapper.BasicShoppingItemMapper;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.mapper.MemberOrderAppMapper;
import com.shycloud.mido.member.mapper.MemberOrderDetailAppMapper;
import com.shycloud.mido.member.mapper.MemberOrderMapper;
import com.shycloud.mido.member.service.AppShoppingMallService;
import com.shycloud.mido.member.service.VipMemberService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Xiaoxing Yu
 * @date 1/29/21 11:26 AM
 **/
@Slf4j
@Service
@AllArgsConstructor
public class AppShoppingMallServiceImpl extends
		ServiceImpl<BasicGoodsInfoMapper, BasicGoodsInfo> implements AppShoppingMallService {

	private BasicProductsComboMapper comboMapper;
	/** Goods Mapper */
	private BasicGoodsInfoMapper goodsInfoMapper;
	/** Goods-category Mapper */
	private BasicGoodsCategoryMapper categoryMapper;
	/** 购物车 Mapper */
	private BasicShoppingCartMapper shoppingCartMapper;
	/** 商城商品 Mapper */
	private BasicShoppingItemMapper shoppingItemMapper;
	/** 订单 Mapper */
	private MemberOrderAppMapper orderMapper;
	/** 订单详情 Mapper */
	private MemberOrderDetailAppMapper orderDetailMapper;
	/** 会员 Mapper */
	private MemberMapper memberMapper;
	/** 商城 banner Mapper */
	private BasicShoppingBannerMapper bannerMapper;
	/** music feign service */
	private RemoteMusicService remoteMusicService;
	/** 商品类别 mapper */
	private BasicProductInfoMapper productInfoMapper;
	/** 订单模块 mapper */
	private final MemberOrderMapper memberOrderMapper;
	/** vip会员模块 service */
	private VipMemberService vipMemberService;
	/** 有声书扫码激活业务 Mapper */
	private BaseMusicAuditionCodeMapper baseMusicAuditionCodeMapper;

	@Override
	public Map getAllGoods() {

		try {

			//构造返回体
			Map returnMap = new HashMap(3);
			//硬件商品
			List<GoodsInfoVO> hardwareList = goodsInfoMapper.selectHardwareGoodsV2(null);
			for (GoodsInfoVO goodsInfoVO : hardwareList) {
				List<BasicShoppingBanner> bannerImg = goodsInfoMapper
						.getBannerImg(goodsInfoVO.getGoodsId());
				goodsInfoVO.setBanners(bannerImg);
			}
			returnMap.put("hardware", hardwareList);
			//VIP商品
			List<GoodsInfoVO> vipList = goodsInfoMapper.selectVipGoods(null);
			returnMap.put("vip", vipList);
			//优惠券
			List<GoodsInfoVO> couponList = goodsInfoMapper.selectCouponList(null);
			returnMap.put("coupon", couponList);

			return returnMap;

		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R addToCart(AppAppShoppingCartVO appShoppingCartVO) {
		BasicAppShoppingCart cartEntity = null;
		try {
			if (appShoppingCartVO.getCollectionId() != null) {
				//判断是否为会员，若为会员无需购买
				//是否是会员
				//VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(SecurityUtils.getMember().getId());

//				if ("1".equals(vipMemberVO.getIsVipString())) {
//					throw new BusinessException("您已经是会员身份，无需购买曲集");
//				}

				//查看是否已经购买该曲集
				Integer isBuy = memberOrderMapper
						.checkIsByCollection(SecurityUtils.getMember().getId(),
								appShoppingCartVO.getCollectionId());

				if (isBuy > 0) {
					throw new BusinessException("您已经购买过该曲集，无需重复购买");
				}
			}
			//看购物车是否已经有此物品
			BasicAppShoppingCart existing =
					shoppingCartMapper.selectExistingItem(
							SecurityUtils.getMember().getId(), appShoppingCartVO.getGoodsId(),
							appShoppingCartVO.getCollectionId());

			if (existing != null) {
				if (appShoppingCartVO.getGoodsId() != null) {
					//增加数量
					existing.setQuantity(existing.getQuantity() + appShoppingCartVO.getQuantity());

					int updateRes = shoppingCartMapper.updateById(existing);

					return new R(CommonConstants.SUCCESS, "已添加到购物车", updateRes == 1 ? true : false);
				} else if (appShoppingCartVO.getCollectionId() != null) {
					//已经有该曲集 添加失败
					return new R(CommonConstants.SUCCESS, "该曲集已在购物车内，请勿重复添加!", false);
				}
			}

			String memberId = SecurityUtils.getMember().getId();

			BasicAppShoppingItem item = shoppingItemMapper.selectOne(
					new QueryWrapper<BasicAppShoppingItem>()
							.eq("collection_id", appShoppingCartVO.getCollectionId())
							.or().eq("goods_id", appShoppingCartVO.getGoodsId()));

			cartEntity = new BasicAppShoppingCart();

			BeanUtils.copyProperties(appShoppingCartVO, cartEntity);

			if (item != null) {
				cartEntity.setItemId(item.getId());
			} else {
				BasicAppShoppingItem itemEntity = new BasicAppShoppingItem();
				if (appShoppingCartVO.getCollectionId() != null) {
					itemEntity.setCollectionId(appShoppingCartVO.getCollectionId());
				}

				if (appShoppingCartVO.getGoodsId() != null) {
					itemEntity.setGoodsId(appShoppingCartVO.getGoodsId());
				}

				itemEntity.setUnitGoldPrice(appShoppingCartVO.getUnitGoldPrice());

				shoppingItemMapper.insert(itemEntity);
				cartEntity.setItemId(itemEntity.getId());
			}

			cartEntity.setMemberId(memberId);
			cartEntity.setQuantity(appShoppingCartVO.getQuantity());
			cartEntity.setCreateTime(LocalDateTime.now());

			shoppingCartMapper.insert(cartEntity);
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return new R(CommonConstants.FAIL, "购物车添加失败，内部系统错误", false);
		}

		return new R(CommonConstants.SUCCESS, "购物车添加成功!", true);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean createOrder(AppShoppingOrderVO orderVO) {
		Map returnMap = createOrderActual(orderVO);
		return (Boolean) returnMap.get("result");
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	protected Map createOrderActual(AppShoppingOrderVO orderVO) {
		Map returnMap = new HashMap();

		MemberOrderApp orderEntity = new MemberOrderApp();
		BeanUtils.copyProperties(orderVO, orderEntity);
		orderEntity.setCreateTime(LocalDateTime.now());

		if (orderVO.getUserPhone() != null) {
			Member member = memberMapper
					.selectOne(new QueryWrapper<Member>().eq("username", orderVO.getUserPhone()));
			orderEntity.setMemberId(
					member != null ? member.getId() : String.valueOf(orderVO.getUserPhone()));
		} else {
			orderEntity.setMemberId(SecurityUtils.getMember().getId());
		}

		orderEntity.setGold(orderVO.getTotalGoldPrice());
		orderEntity.setType("0");
		orderEntity.setStatus(orderVO.getFromSy() != null && orderVO.getFromSy() ? "2" : "1");

		//雪花算法生成全局唯一orderNo
		Integer machineId = ShoppingStockConstants.getConsistentHash(NetworkUtil.getHostIp());
		long orderNo = new SnowFlakeUtil(1, machineId).nextId();
		log.info("APP商城购买生成订单编号为: " + orderNo);
		orderEntity.setOrderNo(orderNo);
		orderMapper.insert(orderEntity);

		for (BasicAppShoppingOrder item : orderVO.getShoppingItems()) {
			MemberOrderDetailApp detailEntity = new MemberOrderDetailApp();
			BeanUtils.copyProperties(item, detailEntity);
			detailEntity.setOrderNo(orderNo);
			boolean isSy = orderVO.getFromSy() != null && orderVO.getFromSy();
			detailEntity.setCollectionType(isSy ? 1 : 0);
			//TODO 购买类型
			detailEntity.setPurchaseType(
					item.getCollectionId() != null ? "1" : (item.getGoodsId() != null ? "3" : "2"));
			detailEntity.setCollectionId(
					isSy ? baseMusicAuditionCodeMapper.getCollectionIdBySyId(item.getSyId())
							: item.getCollectionId());
			if (item.getGoodsId() != null) {
				detailEntity.setGoodsId(item.getGoodsId());
			}

			if (1 != orderDetailMapper.insert(detailEntity)) {
				throw new BusinessException("创建订单失败");
			}
		}

		returnMap.put("result", true);
		returnMap.put("consumeGold", orderVO.getTotalGoldPrice());
		returnMap.put("orderNo", orderNo);

		return returnMap;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public R purchase(AppShoppingPurchaseVO purchaseVO) {
		try {
			if (purchaseVO.getShoppingItems() == null
					|| purchaseVO.getShoppingItems().size() == 0) {
				throw new BusinessException("没有待购买物品！请查看购物车内是否添加了商品");
			}

			//处理单本曲集购买逻辑
//			if (purchaseVO.getShoppingItems().size() == 1) {
//				List<BasicAppShoppingOrder> orderList = purchaseVO.getShoppingItems();
//
//				if (orderList.get(0).getCollectionId() != null) {
//					//检测是否是VIP
//					VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(SecurityUtils.getMember().getId());
//
//					if ("1".equals(vipMemberVO.getIsVipString())) {
//						throw new BusinessException("您已经是会员身份，无需购买曲集");
//					}
//				}
//			}

			AppShoppingOrderVO orderVO = new AppShoppingOrderVO();

			BeanUtils.copyProperties(purchaseVO, orderVO);

			//创建订单
			Map createOrderMap = createOrderActual(orderVO);

			//减少库存(暂时不需要此逻辑，因为硬件现在由淘宝卖出去，由运营后续在后台补销售单来减库存(统一填总部发出))
//			for (BasicShoppingCart cart: purchaseVO.getShoppingItems()) {
//				BasicGoodsInfo goodsInfo = goodsInfoMapper.selectOne(
//						new QueryWrapper<BasicGoodsInfo>().eq("id", cart.getGoodsId()));
//
//				if ("1".equals(goodsInfo.getType())) {
//					//证明是硬件
//					//减少库存
//				}
//			}

			//扣除快乐贝
			Member memberEntity = memberMapper.selectOne(
					new QueryWrapper<Member>().eq("id", SecurityUtils.getMember().getId()));

			if (memberEntity.getGold() - purchaseVO.getTotalGoldPrice() < 0) {
				//删除购物车
				deleteCartActual(purchaseVO);
				//更新交易状态为交易失败
				Long orderNo = (Long) createOrderMap.get("orderNo");
				MemberOrderApp orderEntity = orderMapper
						.selectOne(new QueryWrapper<MemberOrderApp>().eq("order_no", orderNo));
				orderEntity.setStatus("0");
				orderMapper.updateById(orderEntity);

				return new R(CommonConstants.FAIL, "快乐贝不足，订单交易失败", false);
			}

			memberEntity.setGold(memberEntity.getGold() - purchaseVO.getTotalGoldPrice());

			int insertResult = memberMapper.updateById(memberEntity);

			//更新订单状态
			MemberOrderApp orderEntity = orderMapper.selectOne(
					new QueryWrapper<MemberOrderApp>()
							.eq("order_no", (Long) createOrderMap.get("orderNo")));
			orderEntity.setStatus(insertResult == 1 ? "1" : "0");
			orderEntity.setType(purchaseVO.getType());

			orderMapper.updateById(orderEntity);

			for (BasicAppShoppingOrder order : purchaseVO.getShoppingItems()) {
				if (order.getCollectionId() != null) {
					//追加用户-购买曲集 关系表
					memberOrderMapper.insertMemberBuyCollection(SecurityUtils.getMember().getId(),
							order.getCollectionId(), "1", "0");
				}
			}

			//删除购物车
			deleteCartActual(purchaseVO);

			//添加商品功能 TODO
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return new R(CommonConstants.FAIL, e.getMessage(), false);
		}

		return new R(CommonConstants.SUCCESS, "交易成功", true);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	protected void deleteCartActual(AppShoppingPurchaseVO purchaseVO) {
		List<Long> idList = new ArrayList<>();

		//删除购物车对应已购买物品
		for (BasicAppShoppingOrder order : purchaseVO.getShoppingItems()) {
			if (order.getId() != null) {
				idList.add(order.getId());
			} else {
				AppAppShoppingCartVO existingCart = shoppingCartMapper
						.selectExistingItem(SecurityUtils.getMember().getId(), null,
								order.getCollectionId());

				if (existingCart != null) {
					if (existingCart.getCollectionId() != null) {
						idList.add(existingCart.getId());
					}
				}
			}
		}

		if (idList != null && idList.size() != 0) {
//			if (idList.size() == 1) {
//				shoppingCartMapper.deleteById(idList.get(0));
//			} else {
			shoppingCartMapper.deleteBatchIds(idList);
//			}
		}
	}

	@Override
	public List<AppAppShoppingCartVO> getShoppingCart() {
		return shoppingCartMapper.selectShoppingCart(SecurityUtils.getMember().getId());
	}

	@Override
	public List<MemberOrderAppVO> getOrders(String status) {
		return orderMapper.getAllOrders(SecurityUtils.getMember().getId(), status);
	}

	@Override
	public List<MemberOrderAppVO> searchOrder(String keyword) {
		List<MemberOrderAppVO> searchList = orderMapper
				.searchOrderByKeyWord(keyword, SecurityUtils.getMember().getId());
		return searchList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteCart(List<Integer> idList) {
		for (Integer id : idList) {
			int deleteCount = shoppingCartMapper
					.delete(new QueryWrapper<BasicAppShoppingCart>().eq("id", id));

			if (deleteCount == 0) {
				throw new BusinessException("删除失败！");
			}
		}

		return true;
	}

	//TODO
	@Override
	public Boolean editCart(AppAppShoppingCartVO appShoppingCartVO) {
		return null;
	}

	@Override
	public Map getUserAvail(String memberId) {
		Map returnMap = new HashMap();

		Member member = memberMapper.selectOne(new QueryWrapper<Member>().eq("id", memberId));

		returnMap.put("points", member.getPoints());
		returnMap.put("gold", member.getGold());
		returnMap.put("exp", member.getExp());

		return returnMap;
	}

	@Override
	public Map searchGoods(String keyword) {
		Map returnMap = null;
		List<GoodsInfoVO> hardwareList = null;
		List<GoodsInfoVO> vipList = null;
		List<GoodsInfoVO> couponList = null;

		try {
			returnMap = new HashMap();

			hardwareList = goodsInfoMapper.selectHardwareGoods(keyword);
			vipList = goodsInfoMapper.selectVipGoods(keyword);
			couponList = goodsInfoMapper.selectCouponList(keyword);

			//flg传"1"表示只搜定制曲集 3表示只搜所有曲集 0搜曲集+曲目
			R<Map> collectionResult = remoteMusicService.searchCollection(1, 10, keyword, null);
			Map collectionMap = collectionResult.getData();

//			returnMap.put("hardware", hardwareList);
//			returnMap.put("vip", vipList);
			returnMap.put("coupon", couponList);
			returnMap.put("collection", (Map) collectionMap.get("collection"));

			return returnMap;
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	public List<BasicShoppingBanner> getBanners(Integer goodsId) {

		if (goodsId == null) {
			goodsId = -1;
		}

		return bannerMapper.selectList(
				new QueryWrapper<BasicShoppingBanner>().eq(BasicShoppingBanner.COL_STATUS, 0)
						.eq(BasicShoppingBanner.COL_GOODS_ID, goodsId));
	}

	@Override
	public List<RecommendVO> getRecommend(Integer type) {

		//type 1 曲集 2 商品 不传则曲集+商品
		List<RecommendVO> itemList = shoppingItemMapper.selectRecommendGoods();

		if (type != null) {

			if (type == 1) {
				itemList = shoppingItemMapper.selectRecommendColl();
			}

			Iterator<RecommendVO> iterator = itemList.iterator();
			while (iterator.hasNext()) {

				RecommendVO item = iterator.next();
				if (type == 1) {
					//后台管理新增类型字段
					item.setType("电子书");
					if (item.getGoodsId() != null) {
						iterator.remove();
					}
				} else if (type == 2) {
					//查询 product 表获取商品类型
					BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(item.getGoodsId());
					if (basicGoodsInfo != null) {
						BasicProductInfo basicProductInfo = productInfoMapper
								.selectById(basicGoodsInfo.getProductId());
						if (basicProductInfo != null) {
							item.setType(basicProductInfo.getName());
						}
					}
					if (item.getCollectionId() != null) {
						iterator.remove();
					}
				}
			}
		}
		return itemList;
	}

	@Override
	public AppAppShoppingCartVO getCartByCollection(String memberId, Integer collectionId) {
		return null;
	}
}
